package com.yc.springcloud.service.impl;

import com.yc.springcloud.dao.OrderDao;
import com.yc.springcloud.entity.Order;
import com.yc.springcloud.service.AccountService;
import com.yc.springcloud.service.OrderService;
import com.yc.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * @Author DELL
 * @Date 2024/11/20 14:37
 * @Version 1.0
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

	@Resource
	private OrderDao orderDao;

	@Resource
	private StorageService storageService;

	@Resource
	private AccountService accountService;

	@Override
	/**
	 * 老师解读
	 * 1. @GlobalTransactional : 分布式全局事务控制  io.seata.spring.annotation包
	 * 2. name = "yc_order_service_save" 名称，程序员自己指定,保证唯一即可
	 * 3. rollbackFor = Exception.class 指定发送什么异常就回滚, 这里我们指定的是Exception.class
	 *    即 只要发生了异常就回滚
	 */
	@GlobalTransactional(name = "yc_order_service_save",rollbackFor = Exception.class)
	public void save(Order order) {

		log.info("=========Order save START=========");
		orderDao.save(order);

		log.info("=========减库存 start ==========");
		storageService.reduce(order.getProductId(), order.getNums());
		log.info("=========减库存 end ==========");

		log.info("=========减账户金额 start ==========");
		accountService.reduce(order.getUserId(), order.getMoney());
		log.info("=========减账户金额 end ==========");

		log.info("=========修改订单状态 start ==========");
		orderDao.update(order.getUserId(), 0);
		log.info("=========修改订单状态 end ==========");

		log.info("=========Order save END=========");

	}

}
